const Sequelize = require('sequelize')
const db = require('./db')
const User = db.define(
  'user',
  { name: Sequelize.STRING },
  {
    tableName: 'user'
  }
)
const Task = db.define(
  'task',
  { name: Sequelize.STRING },
  {
    tableName: 'task'
  }
)
// 中间表
const Tool = db.define(
  'tool',
  { name: Sequelize.STRING },
  {
    tableName: 'tool'
  }
)
const Player = db.define(
  'player',
  {name: Sequelize.STRING},
  {
    tableName: 'player'
  }
)
const Project = db.define(
  'project',
  { name: Sequelize.STRING },
  {
    tableName: 'project'
  }
)

// 好。 现在，事情变得更加复杂（对用户来说并不真实可见）。
// 首先我们来定义一个 hasMany 关联
Project.hasMany(Player, { as: 'Workers' })

const City = db.define(
  'city',
  { countryCode: Sequelize.STRING },
  { tableName: 'city' }
)
const Country = db.define(
  'country',
  { isoCode: Sequelize.STRING },
  { tableName: 'country' }
)

// 在这里，我们可以根据国家代码连接国家和城市
Country.hasMany(City, { foreignKey: 'countryCode', sourceKey: 'isoCode' })
City.belongsTo(Country, { foreignKey: 'countryCode', targetKey: 'isoCode' })

Task.belongsTo(User)
User.hasMany(Task, { as: 'Task', otherKey: 'id' })
User.hasMany(Tool, { as: 'Instruments', otherKey: 'id' })
// Task.sync({ force: false })
// Tool.sync({ force: false })
// User.sync({ force: false })
db.sync({ force: false }).then(() => {
  Player.findAll({
    // include: [Project]
  }).then(player => {
    console.log(JSON.stringify(player))
  })
  // 这是我们继续的地方 ...
  // Task.findAll({ include: [User] }).then(tasks => {
  //   console.log(JSON.stringify(tasks))
  // })
})
